package org.wukongcrm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.wukongcrm.domain.entity.Address;
import org.wukongcrm.mapper.AddressMapper;
import org.wukongcrm.service.AddressService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService{

    @Override
    public List<Address> getAddressTree() {
        // 查询所有地址数据
        List<Address> allAddresses = baseMapper.selectList(null);
        // 构建树形结构
        Map<String, Address> addressMap = new HashMap<>();
        List<Address> rootAddresses = new ArrayList<>();

        // 先将所有地址放入 Map 中，方便查找
        for (Address address : allAddresses) {
            addressMap.put(address.getAddressAreaid(), address);
        }

        // 构建树形结构
        for (Address address : allAddresses) {
            String regionId = address.getAddressRegionid();
            Address parent = addressMap.get(regionId);
            if (parent == null || address.getAddressAreaid().equals(regionId)) {
                rootAddresses.add(address);
            } else {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(address);
            }
        }
        return rootAddresses;
    }

}
